<template>
  <keep-alive>
    <div class="cart">
      <van-cell>
        <span v-if="isEdit" @click="onEdit()">编辑</span>
        <span v-else @click="onEdit()">完成</span>
      </van-cell>
      <van-checkbox-group
        @change="checkedResultChange"
        v-model="checkedResult"
        v-if="cart.cartList.length > 0 && isEdit"
      >
        <div class="cart-item" v-for="item in cart.cartList" :key="item.id">
          <van-checkbox :name="item.productId" class="cart-checkbox"></van-checkbox>
          <van-card
            :num="item.number"
            :price="item.price"
            :title="item.goodsName"
            :thumb="item.picUrl"
            class="cart-card"
          >
            <template #tags>
              <van-tag
                plain
                type="primary"
                v-for="goods in item.specifications"
                :key="goods"
                >{{ goods }}</van-tag
              >
            </template>
            <template #footer>
              <div>添加日期 {{ item.addTime }}</div>
            </template>
          </van-card>
        </div>
      </van-checkbox-group>
      <van-checkbox-group
        @change="checkedResultChange"
        v-model="checkedResult"
        v-else-if="cart.cartList.length > 0 && !isEdit"
      >
        <div class="cart-item" v-for="item in cart.cartList" :key="item.id">
          <van-checkbox :name="item.productId" class="cart-checkbox"></van-checkbox>
          <van-card
            :num="item.number"
            :price="item.price"
            :title="item.goodsName"
            :thumb="item.picUrl"
            class="cart-card"
          >
            <template #tags>
              <van-tag
                plain
                type="primary"
                v-for="goods in item.specifications"
                :key="goods"
                >{{ goods }}</van-tag
              >
            </template>
            <template #footer>
              <van-stepper v-model="item.number" disable-input @click="updateCart(item.goodsId,item.id,item.number,item.productId)"/>
            </template>
          </van-card>
          <div class="cart-del" @click="delGoods(item.productId)">删除</div>
        </div>
      </van-checkbox-group>
      <van-empty v-else description="你的购物车为空" />
      <van-submit-bar
        :price="totalPrice"
        button-text="结算"
        style="bottom: 50px"
        v-if="isEdit"
      >
        <van-checkbox :checked="isCheckAll"  @click="checkAllChange">全选</van-checkbox>
      </van-submit-bar>
      <van-submit-bar
        :price="totalPrice"
        button-text="删除"
        style="bottom: 50px"
        @submit="delSelectedGoods"
        v-else
      >
        <van-checkbox :checked="isCheckAll"  @click="checkAllChange">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </keep-alive>
</template>

<script setup>
import { onMounted, reactive, ref,computed } from "vue";
import { getCart,postDelate, postUpdate } from "../api";
import { useRouter } from "vue-router";

let router = useRouter();
let cart = reactive({ cartList: [], cartTotal: {} });
const isCheckAll = ref(false);
const checkedResult = ref([]);
let isEdit = ref(true);

const totalPrice = computed(() => {
  return checkedResult.value.reduce((total, id) => {
    const item = cart.cartList.find(item => item.productId === id);
    return total + (item ? item.price * item.number * 100 : 0);
  }, 0);
});

onMounted(async () => {
  let { data, errmsg } = await getCart();
  if (errmsg === "请登录" || !localStorage.getItem("userInfo")) {
    showToast('请先登录');
    router.push("/login");
  }
  cart.cartList = data.cartList;
  cart.cartTotal = data.cartTotal;
});

const onEdit = () => {
  isEdit.value = !isEdit.value;
};

const checkAllChange = () => {
  isCheckAll.value = !isCheckAll.value;
  checkedResult.value = isCheckAll.value ? cart.cartList.map(item=>item.productId) : [];
};

const checkedResultChange = (value) => {
   checkedResult.value = value;
   isCheckAll.value = value.length === cart.cartList.length;
};

const delGoods = async (data) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除这个商品吗？',
    });
    await postDelate({productIds:[data]});
    showSuccessToast('删除成功!');

    cart.cartList = cart.cartList.filter(item => item.productId !== data);
    checkedResult.value = checkedResult.value.filter(itemId => itemId !== data);
  } catch (error) {
    if (error === 'cancel') {
      return;
    }
    console.error('删除商品失败:', error);
  }
};

const delSelectedGoods = async () => {
  if (checkedResult.value.length === 0){ 
    showToast('至少选择一个商品');
    return};
  
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除选中的商品吗？`,
    });
    await postDelate({productIds:checkedResult.value});
    showSuccessToast('删除成功!');
    checkedResult.value = []; 
    cart.cartList = cart.cartList.filter(item => !checkedResult.value.includes(item.productId));
    checkedResult.value = [];
  } catch (error) {
    if (error === 'cancel') {
      return;
    }
    console.error('删除商品失败:', error);
  }
};

//更新商品数量
const updateCart = async(goodsId,id,number,productId) => {
  try {
    console.log("111");
    
    await postUpdate({goodsId,id,number,productId});
  } catch (error) {
    console.log(error);
  }
}
</script>

<style scoped>
.van-cell {
  flex-shrink: 0;
}
.van-checkbox-group {
  padding-bottom: 100px;
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  height: 100vh;
  position: relative;
}
.cart-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  margin-bottom: 10px;
}

.cart-checkbox {
  flex-shrink: 0;
  margin-right: 10px;
  margin-left: 10px;
}

.cart-card {
  flex-grow: 1;
  background: #fff;
}
.cart-del {
  line-height: 100px;
  padding: 0 10px;
  color: #fff;
  background-color: #db3d3c;
}
</style>